package com.songx64.commonutils;

import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import java.util.HashMap;
import java.util.Map;

/**
 * Created on 2021/1/10,下午 7:21
 *
 * @author SongX64
 * 统一结果返回类
 */
@Data
public class R {

    @ApiModelProperty(value = "是否成功")
    private Boolean success;

    @ApiModelProperty("响应码")
    private Integer code;

    @ApiModelProperty("返回消息")
    private String message;

    @ApiModelProperty("返回数据")
    private Map<String, Object> data = new HashMap<String, Object>();

    //构造方法私有化
    private R() {
    }

    //成功静态方法，设置对象值为成功然后返回
    public static R ok() {
        R r = new R();
        r.setSuccess(true);
        r.setCode(ResultCode.SUCCESS);
        r.setMessage("成功");
        return r;
    }

    //失败静态方法，同上
    public static R error() {
        R r = new R();
        r.setSuccess(false);
        r.setCode(ResultCode.ERROR);
        r.setMessage("失败");
        return r;
    }

    //重载状态码
    public R code(Integer code) {
        this.setCode(code);
        return this;
    }

    //重载消息
    public R success(String message) {
        this.setMessage(message);
        return this;
    }

    public R error(String message) {
        this.setMessage(message);
        return this;
    }

    //重载数据
    public R data(String key, Object value) {
        this.data.put(key, value);
        return this;
    }

    public R data(Map<String, Object> data) {
        this.setData(data);
        return this;
    }
}
